package com.developer.platform.infrastructure.security;

import cn.hutool.core.collection.CollUtil;
import com.developer.platform.domain.security.AuthorizationInfo;
import com.developer.platform.domain.service.IAuthorizationSource;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

/**
 * 安全拦截器- 拦截访问url所需资源-权限
 *
 * @author ：qiaoliang
 * @date ：2020-11-04
 */
@Component
public class SecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    private final IAuthorizationSource authorizationResource;

    public SecurityMetadataSource(IAuthorizationSource authorizationResource) {
        this.authorizationResource = authorizationResource;
    }

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //  获取当前请求request
        HttpServletRequest request = ((FilterInvocation) object).getRequest();
        //  获取url权限信息
        List<AuthorizationInfo> authorizationInfos = authorizationResource.loadResourceDefine();
        return this.requestMakerHandle(authorizationInfos,request);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

    /**
     *  解析认证，获取当前request请求所需权限
     *
     * @author ：qiaoliang
     * @param authorizationInfos : 资源-权限
     * @param request : 当前请求request
     * @return java.lang.String
     * @date 2020-11-04 08:48
     */
    public List<ConfigAttribute> requestMakerHandle(List<AuthorizationInfo> authorizationInfos,
                                                    HttpServletRequest request){
        //  获取访问资源所需权限
        if(CollUtil.isNotEmpty(authorizationInfos)){
            for (AuthorizationInfo authorizationInfo : authorizationInfos) {
                if(authorizationInfo.matches(request)){
                    return SecurityConfig.createList(authorizationInfo.getMark());
                }
            }
        }
        return null;
    }

}
